import { buildUrl, obj2pms } from '@mtjs/utils/es/urlUtil';
import { storage } from '@/plugins/storage';
export { cookies } from './cookies';
export { formatTime } from './time';

export const isOnline = () => {
  return window.location.hostname.endsWith('.com');
};

/**
 * 获取OSS路径
 * @param {string} path 路径
 * @returns 返回拼装后的完整路径
 */
export const getOSSBaseUrl = (path = '') => {
  if (path.startsWith('http')) return path;
  const onlineOssUrl = 'https://img.mytijian.com/';
  const testOssUrl = 'https://test-i.oss-cn-shanghai.aliyuncs.com/';

  return (isOnline() ? onlineOssUrl : testOssUrl) + path;
};

/**
 * 跳转到老项目的方法
 * @param {string} path 页面地址 如 /login
 * @param {string} prefix 项目前缀 如： /m 或 /m/v2
 * @example toPage('/login', '/m') => /m/mt/login
 */
export const toPage = (path, params = {}, prefix = '/m') => {
  const site = storage.get('site') || 'mt';
  const { hospitalId = '' } = storage.get('profile') || {};

  if (prefix === '/m') {
    const pms = obj2pms({ ...params, _from: 'health', _homeUrl: '/' });
    window.location.href = `${prefix}/${site}${path}?${pms}`;
  } else {
    const pms = obj2pms({
      ...params,
      siteOnly: true,
      chunk: 'kru2s5p1',
      _site: site,
      _siteid: hospitalId,
      _homeUrl: '/',
      _from: 'health',
    });
    window.location.href = `${prefix}${path}?${pms}`;
  }
};

/**
 * 跳转到每天C端页面的方法
 * @param {string} opstions.path 页面路径
 * @param {string} opstions.prefix 页面前缀 /m 或 /m/v2
 * @param {string} opstions.site 渠道标识
 * @param {string} opstions.hospitalId 渠道ID
 * @param {string} opstions._from 平台来源
 * @param {string} opstions.homeUrl 返回首页地址 要encode
 */
export const toMTPage = (options) => {
  const { path, prefix, site, hospitalId, _from = '', homeUrl = '', params = {} } = options;
  if (prefix === '/m') {
    const pms = obj2pms({ ...params, _from, homeUrl });
    window.location.href = `${prefix}/${site}${path}?${pms}`;
  } else {
    const pms = obj2pms({
      ...params,
      siteOnly: true,
      _site: site,
      _siteid: hospitalId,
      chunk: 'kru2s5p1',
      _from,
      homeUrl,
    });
    window.location.href = `${prefix}${path}?${pms}`;
  }
};

/**
 * 生成完整的跳转路径
 */
export const buildFullUrl = (url, params) => {
  const origin = window.location.origin;
  return buildUrl(origin + url, params);
};

export const px2rem = (value) => {
  const v = parseFloat(value);
  if (v < 3) return v + 'px';

  const REM = parseFloat(getComputedStyle(document.documentElement).fontSize);
  return (v / REM).toFixed(3) + 'rem';
};

export const rem2px = (value) => {
  const REM = parseFloat(getComputedStyle(document.documentElement).fontSize);
  return parseFloat(value) * REM + 'px';
};

export const safeJSONParse = (str) => {
  let res = '';
  try {
    res = JSON.parse(str);
  } catch (error) {
    res = '';
  }
  return res;
};
